package icasue.base.utils.script;

import icasue.base.utils.wareable.CLog;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 *  1、内嵌编译器如"PythonInterpreter"无法引用扩展包，因此推荐使用java调用控制台进程方式"Runtime.getRuntime().exec()"来运行脚本(shell或python)；
 *  2、因为通过java调用控制台进程方式实现，需要保证目标机器PATH路径正确配置对应编译器；
 *  3、暂时脚本执行日志只能在脚本执行结束后一次性获取，无法保证实时性；因此为确保日志实时性，可改为将脚本打印的日志存储在指定的日志文件上；
 *  4、python 异常输出优先级高于标准输出，体现在Log文件中，因此推荐通过logging方式打日志保持和异常信息一致；否则用prinf日志顺序会错乱
 *
 * Created by QiaoHang.
 */
public final class ScriptUtil {

    /**
     * By this wey, Shells script's execution depend on Linux env, will find explain programing on #!/bin/bash sh
     * @param shellFile
     * @param shellLog
     * @param content
     * @param params
     * @return
     * @throws IOException
     */
    public static int execShell(String shellFile, String shellLog, String content,String... params) throws IOException {
        markScriptFile(shellFile,content);
        // #!/bin/bash sh
        int sh = execToFile("sh", shellFile, shellLog, params);
        return sh;
    }

    /**
     * By this wey, Pythons script's execution depend on Linux env, will find explain programing on #!/bin/bash python
     * @param pythonFile
     * @param pythonLog
     * @param content
     * @param params
     * @return
     * @throws IOException
     */
    public static int execPython(String pythonFile, String pythonLog, String content,String... params) throws IOException {
        markScriptFile(pythonFile,content);
        // #!/bin/bash python
        int py = execToFile("python", pythonFile, pythonLog, params);
        return py;
    }

    /**
     * By this wey, Cs script's execution depend on Linux env, will find explain programing on #!/bin/bash gcc
     * @param cFile
     * @param cLog
     * @param content
     * @param params
     * @return
     * @throws IOException
     */
    public static int execC(String cFile, String cLog, String content,String... params) throws IOException {
        markScriptFile(cFile,content);
        String cFileOut = cFile.concat(".out");
        // #!/bin/bash gcc
        int cCompile = execToFile("gcc", cFile, cLog, "-o",cFileOut);
        int cExec = execToFile(null, cFileOut, cLog, params);
        return cCompile | cExec;
    }

    /**
     * make script file
     *
     * @param scriptFileName
     * @param content
     * @throws IOException
     */
    public static void markScriptFile(String scriptFileName, String content) throws IOException {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(scriptFileName);
            fileOutputStream.write(content.getBytes("UTF-8"));
            fileOutputStream.close();
        } catch (Exception e) {
            throw e;
        }finally{
            if(fileOutputStream != null){
                fileOutputStream.close();
            }
        }
    }

    /**
     * Common script execution, ignore server's type, boss Windows, Mac, Linux.
     * @param command
     * @param scriptFile
     * @param logFile
     * @param params
     * @return
     * @throws IOException
     */
    public static int execToFile(String command, String scriptFile, String logFile, String... params) throws IOException {

        FileOutputStream fileOutputStream = null;
        Thread inputThread = null;
        Thread errThread = null;
        try {
            // file
            fileOutputStream = new FileOutputStream(logFile, true);

            // command
            List<String> cmdarray = new ArrayList<>();

            if(command != null){
                cmdarray.add(command);
            }
            cmdarray.add(scriptFile);
            if (params!=null && params.length>0) {
                for (String param:params) {
                    cmdarray.add(param);
                }
            }
            String[] cmdarrayFinal = cmdarray.toArray(new String[cmdarray.size()]);

            // process-exec
            final Process process = Runtime.getRuntime().exec(cmdarrayFinal);

            // log-thread
            final FileOutputStream finalFileOutputStream = fileOutputStream;
            inputThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        copy(process.getInputStream(), finalFileOutputStream, new byte[1024]);
                    } catch (IOException e) {
                        CLog.error(e.getMessage());
                    }
                }
            });
            errThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        copy(process.getErrorStream(), finalFileOutputStream, new byte[1024]);
                    } catch (IOException e) {
                        CLog.error(e.getMessage());
                    }
                }
            });
            inputThread.start();
            errThread.start();

            // process-wait
            int exitValue = process.waitFor();      // exit code: 0=success, 1=error

            // log-thread join
            inputThread.join();
            errThread.join();

            return exitValue;
        } catch (Exception e) {
            CLog.error(e.getMessage());
            return -1;
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    CLog.error(e.getMessage());
                }

            }
            if (inputThread != null && inputThread.isAlive()) {
                inputThread.interrupt();
            }
            if (errThread != null && errThread.isAlive()) {
                errThread.interrupt();
            }
        }
    }

    /**
     * Data stream's copy, all InputStream will close after received, Log's OutputStream will keep opening.
     * @param inputStream
     * @param outputStream
     * @param buffer
     * @return
     * @throws IOException
     */
    private static long copy(InputStream inputStream, OutputStream outputStream, byte[] buffer) throws IOException {
        try {
            long total = 0;
            for (;;) {
                int res = inputStream.read(buffer);
                if (res == -1) {
                    break;
                }
                if (res > 0) {
                    total += res;
                    if (outputStream != null) {
                        outputStream.write(buffer, 0, res);
                    }
                }
            }
            outputStream.flush();
            //out = null;
            inputStream.close();
            inputStream = null;
            return total;
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    public static void main(String[] args) {
        String shell = "#!/bin/bash sh\n" +
                "echo 'hello casue'";
        String shellLog = "/Users/icasue/Desktop/lbs-server-plugins/lbs-plugin-base/file/output/sh.log";
        String shellFile = "/Users/icasue/Desktop/lbs-server-plugins/lbs-plugin-base/file/script/sh.sh";
        try {
            int i = execShell(shellFile, shellLog, shell, null);
            System.out.println("----");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
    public static void main(String[] args) {
        try {
            String cScriptFile = "/Users/icasue/Desktop/lbs-server-plugins/lbs-plugin-base/file/script/demo.c";
            String cLogFile = "/Users/icasue/Desktop/lbs-server-plugins/lbs-plugin-base/file/output/demo.log";
            String cScript = "#include <stdio.h>\n" +
                    "\n" +
                    "\n" +
                    "int main(){\n" +
                    "\tint i = 0;\n" +
                    "\tfor(;i<10;i++){\n" +
                    "\t\tprintf(\"当前值为：%d\\n\",i);\n" +
                    "\t}\n" +
                    "\treturn i;\n" +
                    "}\n";
            //  "gcc ./hello.c -o ./hello.c.out2 && ./hello.c.out2"
            int i = execC(cScriptFile, cLogFile, cScript, null);
        }catch (Throwable e){
            System.out.println("-----");
        }
    }


    public static void main(String[] args) {
        try {
            String scriptFile = "/Users/icasue/Desktop/lbs-server-plugins/lbs-plugin-base/file/script/hello.sh";
            String logFile = "/Users/icasue/Desktop/lbs-server-plugins/lbs-plugin-base/file/output/shell.log";
            String script = "name=casue\n" +
                    "  \n" +
                    "echo $name\n" +
                    "echo \"hello, \"${name}\n" +
                    "echo \"hello, ${name}\"\n" +
                    "echo \"hello, $name\"\n" +
                    "echo 'hello, '${name}\n" +
                    "echo 'hello ${name}'";
            //  "gcc ./hello.c -o ./hello.c.out2 && ./hello.c.out2"
            int i = execShell(scriptFile, logFile, script, null);
        }catch (Throwable e){
            System.out.println("-----");
        }
    }

    public static void main(String[] args) {
        try {
            String scriptFile = "/Users/icasue/Desktop/lbs-server-plugins/lbs-plugin-base/file/script/test.py";
            String logFile = "/Users/icasue/Desktop/lbs-server-plugins/lbs-plugin-base/file/output/python.log";
            String script = "import time;\n" +
                    "print('-------python login--------');\n" +
                    "print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()));\n" +
                    "name = 'zhouzhou';\n" +
                    "if name == 'casue' :\n" +
                    "        print('casue');\n" +
                    "elif name == 'zhouzhou' :\n" +
                    "        print('zhouzhou');\n" +
                    "else:\n" +
                    "        print('others');\n" +
                    "print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()));\n";
            //  "gcc ./hello.c -o ./hello.c.out2 && ./hello.c.out2"
            int i = execPython(scriptFile, logFile, script, null);
        }catch (Throwable e){
            System.out.println("-----");
        }
    }*/

}
